package com.taxx.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taxx.config.TaxReportConfig;
import com.taxx.controller.dto.*;
import com.taxx.dto.TaxPlatformRequest;
import com.taxx.dto.TaxReportRequest;
import com.taxx.dto.TaxReportResult;
import com.taxx.entity.TaxApiLog;
import com.taxx.entity.TaxIdentityReport;
import com.taxx.entity.TaxIncomeReport;
import com.taxx.entity.TaxPlatformReport;
import com.taxx.enums.ReportStatusEnums;
import com.taxx.mapper.TaxApiLogMapper;
import com.taxx.mapper.TaxIdentityReportMapper;
import com.taxx.mapper.TaxIncomeReportMapper;
import com.taxx.mapper.TaxPlatformReportMapper;
import com.taxx.service.DecryptService;
import com.taxx.service.TaxReportService;
import com.taxx.util.DataCompressionUtil;
import com.taxx.util.Sm4Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 税务报送服务实现类
 *
 * @author taxx
 * @since 2024-01-01
 */
@Slf4j
@Service
public class TaxReportServiceImpl implements TaxReportService {

    @Autowired
    private TaxIncomeReportMapper taxIncomeReportMapper;

    @Autowired
    private TaxIdentityReportMapper taxIdentityReportMapper;

    @Autowired
    private TaxPlatformReportMapper taxPlatformReportMapper;

    @Autowired
    private TaxApiLogMapper taxApiLogMapper;

    @Autowired
    private TaxReportConfig taxReportConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DecryptService decryptService;

    @Override
    public Map<String, Object> reportIdentityData(TaxIdentityReportReqDTO identityReportReqDTO) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        int totalBatches = 0;
        int successBatches = 0;
        int failBatches = 0;

        try {
            // 查询所有待报送的数据
            QueryWrapper<TaxIdentityReport> queryWrapper = new QueryWrapper<>();
            if (Objects.nonNull(identityReportReqDTO.getId()) || Objects.nonNull(identityReportReqDTO.getBatchCode())) {
                queryWrapper.eq(Objects.nonNull(identityReportReqDTO.getId()), "id", identityReportReqDTO.getId());
                queryWrapper.eq(Objects.nonNull(identityReportReqDTO.getBatchCode()), "batch_code", identityReportReqDTO.getBatchCode());
            } else {
                queryWrapper.eq("report_status", 0);
            }
            List<TaxIdentityReport> allReports = taxIdentityReportMapper.selectList(queryWrapper);

            if (allReports.isEmpty()) {
                result.put("success", true);
                result.put("message", "没有待报送的身份信息数据");
                result.put("totalCount", 0);
                result.put("successCount", 0);
                result.put("failCount", 0);
                result.put("totalBatches", 0);
                result.put("successBatches", 0);
                result.put("failBatches", 0);
                return result;
            }

            // 按2000条一批进行拆分
            int maxBatchSize = 2000;
            List<List<TaxIdentityReport>> batches = splitIntoBatches(allReports, maxBatchSize);
            totalBatches = batches.size();

            log.info("身份信息报送：总数据{}条，拆分为{}个批次", allReports.size(), totalBatches);

            String errorMessage = null;
            for (int batchIndex = 0; batchIndex < batches.size(); batchIndex++) {
                List<TaxIdentityReport> batchReports = batches.get(batchIndex);

                // 检查单批次是否超过2000条
                if (batchReports.size() > maxBatchSize) {
                    log.warn("批次{}超过2000条限制，跳过处理，实际数量：{}", batchIndex + 1, batchReports.size());
                    failBatches++;
                    failCount += batchReports.size();
                    continue;
                }

                try {
                    // 更新批次中所有记录状态为报送中
                    for (TaxIdentityReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.SUBMITTING.getCode());
                        taxIdentityReportMapper.updateById(report);
                    }

                    // 构建批量报送请求
                    TaxReportRequest.IdentityReportRequest request = buildBatchIdentityReportRequest(batchReports);

                    // 构建压缩后的报送请求
                    DataCompressionUtil.TaxReportRequestWrapper compressedRequest =
                            DataCompressionUtil.buildTaxReportRequest(taxReportConfig.getIdentityBusinessType(), request);

                    // 调用报送接口
                    TaxReportResult reportResult = callTaxReportApi("身份信息报送", taxReportConfig.getIdentityReportUrl(), compressedRequest, batchIndex);
                    errorMessage = reportResult.getDetailedErrorMessage();
                    if (reportResult.isSuccess()) {
                        // 批量更新成功状态
                        for (TaxIdentityReport report : batchReports) {
                            report.setReportStatus(ReportStatusEnums.SUBMIT_SUCCESS.getCode()); // 报送成功
                            report.setReportTime(LocalDate.now());
                            report.setReportMessage("报送成功");
                            taxIdentityReportMapper.updateById(report);
                        }
                        successBatches++;
                        successCount += batchReports.size();
                        log.info("批次{}报送成功，明细数量：{}", batchIndex + 1, batchReports.size());
                    } else {
                        // 批量更新失败状态
                        for (TaxIdentityReport report : batchReports) {
                            report.setReportStatus(ReportStatusEnums.SUBMIT_FAIL.getCode()); // 报送失败
                            report.setReportTime(LocalDate.now());
                            report.setReportMessage(reportResult.getDetailedErrorMessage());
                            taxIdentityReportMapper.updateById(report);
                        }
                        failBatches++;
                        failCount += batchReports.size();
                        log.error("批次{}报送失败，明细数量：{}，错误信息：{}", batchIndex + 1, batchReports.size(), reportResult.getDetailedErrorMessage());
                    }

                } catch (Exception e) {
                    log.error("批次{}报送异常，明细数量：{}", batchIndex + 1, batchReports.size(), e);
                    // 批量更新异常状态
                    for (TaxIdentityReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.SUBMIT_FAIL.getCode()); // 报送失败
                        report.setReportMessage("报送异常：" + e.getMessage());
                        taxIdentityReportMapper.updateById(report);
                    }
                    failBatches++;
                    failCount += batchReports.size();
                }
            }

            result.put("success", failCount == 0);
            result.put("message", failCount == 0 ? "身份信息报送完成" : "部分身份信息报送完成");
            result.put("errorMessage", errorMessage);
            result.put("totalCount", allReports.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalBatches", totalBatches);
            result.put("successBatches", successBatches);
            result.put("failBatches", failBatches);

        } catch (Exception e) {
            log.error("报送身份信息失败", e);
            result.put("success", false);
            result.put("message", "报送失败：" + e.getMessage());
        }

        return result;
    }


    @Override
    public Map<String, Object> reportIncomeData(TaxIncomeReportReqDTO incomeReportDTO) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        int totalBatches = 0;
        int successBatches = 0;
        int failBatches = 0;

        try {
            // 查询所有待报送的数据
            QueryWrapper<TaxIncomeReport> queryWrapper = new QueryWrapper<>();
            if (Objects.nonNull(incomeReportDTO.getId()) || Objects.nonNull(incomeReportDTO.getBatchCode())) {
                queryWrapper.eq(Objects.nonNull(incomeReportDTO.getId()), "id", incomeReportDTO.getId());
                queryWrapper.eq(Objects.nonNull(incomeReportDTO.getBatchCode()), "batch_code", incomeReportDTO.getBatchCode());
            } else {
                queryWrapper.eq("report_status", 0);
            }
            List<TaxIncomeReport> allReports = taxIncomeReportMapper.selectList(queryWrapper);

            if (allReports.isEmpty()) {
                result.put("success", true);
                result.put("message", "没有待报送的收入信息数据");
                result.put("totalCount", 0);
                result.put("successCount", 0);
                result.put("failCount", 0);
                result.put("totalBatches", 0);
                result.put("successBatches", 0);
                result.put("failBatches", 0);
                return result;
            }

            // 按2000条一批进行拆分
            int maxBatchSize = 2000;
            List<List<TaxIncomeReport>> batches = splitIntoBatches(allReports, maxBatchSize);
            totalBatches = batches.size();

            log.info("收入信息报送：总数据{}条，拆分为{}个批次", allReports.size(), totalBatches);
            String errorMessage = null;
            for (int batchIndex = 0; batchIndex < batches.size(); batchIndex++) {
                List<TaxIncomeReport> batchReports = batches.get(batchIndex);

                // 检查单批次是否超过2000条
                if (batchReports.size() > maxBatchSize) {
                    log.warn("批次{}超过2000条限制，跳过处理，实际数量：{}", batchIndex + 1, batchReports.size());
                    failBatches++;
                    failCount += batchReports.size();
                    continue;
                }

                try {

                    // 更新批次中所有记录状态为报送中
                    for (TaxIncomeReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.SUBMITTING.getCode());
                        taxIncomeReportMapper.updateById(report);
                    }

                    // 构建批量报送请求
                    TaxReportRequest.IncomeReportRequest request = buildBatchIncomeReportRequest(batchReports);

                    // 构建压缩后的报送请求
                    DataCompressionUtil.TaxReportRequestWrapper compressedRequest =
                            DataCompressionUtil.buildTaxReportRequest(taxReportConfig.getIncomeBusinessType(), request);

                    // 调用报送接口
                    TaxReportResult reportResult = callTaxReportApi("收入信息报送", taxReportConfig.getIncomeReportUrl(), compressedRequest, batchIndex);

                    errorMessage = reportResult.getDetailedErrorMessage();

                    if (reportResult.isSuccess()) {
                        // 批量更新成功状态
                        for (TaxIncomeReport report : batchReports) {
                            report.setReportStatus(ReportStatusEnums.SUBMIT_SUCCESS.getCode()); // 报送成功
                            report.setReportTime(LocalDate.now());
                            report.setReportMessage("报送成功");
                            taxIncomeReportMapper.updateById(report);
                        }
                        successBatches++;
                        successCount += batchReports.size();
                        log.info("批次{}报送成功，明细数量：{}", batchIndex + 1, batchReports.size());
                    } else {
                        // 批量更新失败状态
                        for (TaxIncomeReport report : batchReports) {
                            report.setReportStatus(ReportStatusEnums.SUBMIT_FAIL.getCode()); // 报送失败
                            report.setReportTime(LocalDate.now());
                            report.setReportMessage(reportResult.getDetailedErrorMessage());
                            taxIncomeReportMapper.updateById(report);
                        }
                        failBatches++;
                        failCount += batchReports.size();
                        log.error("批次{}报送失败，明细数量：{}，错误信息：{}", batchIndex + 1, batchReports.size(), reportResult.getDetailedErrorMessage());
                    }

                } catch (Exception e) {
                    log.error("批次{}报送异常，明细数量：{}", batchIndex + 1, batchReports.size(), e);
                    // 批量更新异常状态
                    for (TaxIncomeReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.SUBMIT_FAIL.getCode()); // 报送失败
                        report.setReportMessage("报送异常：" + e.getMessage());
                        taxIncomeReportMapper.updateById(report);
                    }
                    failBatches++;
                    failCount += batchReports.size();
                }
            }

            result.put("success", failCount == 0);
            result.put("message", failCount == 0 ? "收入信息报送完成" : "部分收入信息报送完成");
            result.put("errorMessage", errorMessage);
            result.put("totalCount", allReports.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalBatches", totalBatches);
            result.put("successBatches", successBatches);
            result.put("failBatches", failBatches);

        } catch (Exception e) {
            log.error("报送收入信息失败", e);
            result.put("success", false);
            result.put("message", "报送失败：" + e.getMessage());
        }

        return result;
    }


    @Override
    public Map<String, Object> reportPlatformData(TaxPlatformReportReqDTO platformReportReqDTO) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        int totalBatches = 0;
        int successBatches = 0;
        int failBatches = 0;

        try {
            // 查询所有待报送的数据
            QueryWrapper<TaxPlatformReport> queryWrapper = new QueryWrapper<>();
            if (Objects.nonNull(platformReportReqDTO.getId()) || platformReportReqDTO.getBatchCode() != null) {
                queryWrapper.eq(Objects.nonNull(platformReportReqDTO.getId()), "id", platformReportReqDTO.getId());
                queryWrapper.eq(Objects.nonNull(platformReportReqDTO.getBatchCode()), "batch_code", platformReportReqDTO.getBatchCode());
            } else {
                queryWrapper.eq("report_status", 0);
            }

            List<TaxPlatformReport> allReports = taxPlatformReportMapper.selectList(queryWrapper);

            if (allReports.isEmpty()) {
                result.put("success", true);
                result.put("message", "没有待报送的平台信息数据");
                result.put("totalCount", 0);
                result.put("successCount", 0);
                result.put("failCount", 0);
                result.put("totalBatches", 0);
                result.put("successBatches", 0);
                result.put("failBatches", 0);
                return result;
            }

            // 按2000条一批进行拆分
            int maxBatchSize = 2000;
            List<List<TaxPlatformReport>> batches = splitIntoBatches(allReports, maxBatchSize);
            totalBatches = batches.size();

            log.info("平台信息报送：总数据{}条，拆分为{}个批次", allReports.size(), totalBatches);

            String errorMessage = null;
            for (int batchIndex = 0; batchIndex < batches.size(); batchIndex++) {
                List<TaxPlatformReport> batchReports = batches.get(batchIndex);

                // 检查单批次是否超过2000条
                if (batchReports.size() > maxBatchSize) {
                    log.warn("批次{}超过2000条限制，跳过处理，实际数量：{}", batchIndex + 1, batchReports.size());
                    failBatches++;
                    failCount += batchReports.size();
                    continue;
                }

                try {
                    // 更新批次中所有记录状态为报送中
                    for (TaxPlatformReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.SUBMITTING.getCode());
                        taxPlatformReportMapper.updateById(report);
                    }

                    // 构建批量报送请求
                    TaxReportRequest.PlatformReportRequest request = buildBatchPlatformReportRequest(batchReports);

                    // 构建压缩后的报送请求
                    DataCompressionUtil.TaxReportRequestWrapper compressedRequest =
                            DataCompressionUtil.buildTaxReportRequest(taxReportConfig.getPlatformBusinessType(), request);

                    // 调用报送接口
                    TaxReportResult reportResult = callTaxReportApi("平台信息报送", taxReportConfig.getPlatformReportUrl(), compressedRequest, batchIndex);

                    errorMessage = reportResult.getDetailedErrorMessage();

                    if (reportResult.isSuccess()) {
                        // 批量更新成功状态
                        for (TaxPlatformReport report : batchReports) {
                            report.setReportStatus(ReportStatusEnums.SUBMIT_SUCCESS.getCode()); // 报送成功
                            report.setReportTime(LocalDate.now());
                            report.setReportMessage("报送成功");
                            taxPlatformReportMapper.updateById(report);
                        }
                        successBatches++;
                        successCount += batchReports.size();
                        log.info("批次{}报送成功，明细数量：{}", batchIndex + 1, batchReports.size());
                    } else {
                        // 批量更新失败状态
                        for (TaxPlatformReport report : batchReports) {
                            report.setReportStatus(ReportStatusEnums.SUBMIT_FAIL.getCode()); // 报送失败
                            report.setReportTime(LocalDate.now());
                            report.setReportMessage(reportResult.getDetailedErrorMessage());
                            taxPlatformReportMapper.updateById(report);
                        }
                        failBatches++;
                        failCount += batchReports.size();
                        log.error("批次{}报送失败，明细数量：{}，错误信息：{}", batchIndex + 1, batchReports.size(), reportResult.getDetailedErrorMessage());
                    }

                } catch (Exception e) {
                    log.error("批次{}报送异常，明细数量：{}", batchIndex + 1, batchReports.size(), e);
                    // 批量更新异常状态
                    for (TaxPlatformReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.SUBMIT_FAIL.getCode()); // 报送失败
                        report.setReportMessage("报送异常：" + e.getMessage());
                        taxPlatformReportMapper.updateById(report);
                    }
                    failBatches++;
                    failCount += batchReports.size();
                }
            }

            result.put("success", failCount == 0);
            result.put("message", failCount == 0 ? "平台信息报送完成" : "部分平台信息报送完成");
            result.put("errorMessage", errorMessage);
            result.put("totalCount", allReports.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalBatches", totalBatches);
            result.put("successBatches", successBatches);
            result.put("failBatches", failBatches);

        } catch (Exception e) {
            log.error("报送平台信息失败", e);
            result.put("success", false);
            result.put("message", "报送失败：" + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> retryFailedReport(String dataType) {
        Map<String, Object> result = new HashMap<>();

        try {
            switch (dataType.toLowerCase()) {
                case "income":
                    result = reportIncomeData(new TaxIncomeReportReqDTO());
                    break;
                case "identity":
                    result = reportIdentityData(new TaxIdentityReportReqDTO());
                    break;
                case "platform":
                    result = reportPlatformData(new TaxPlatformReportReqDTO());
                    break;
                default:
                    result.put("success", false);
                    result.put("message", "不支持的数据类型：" + dataType);
            }
        } catch (Exception e) {
            log.error("重试失败报送失败，数据类型：{}", dataType, e);
            result.put("success", false);
            result.put("message", "重试失败：" + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> cancelIdentityData(TaxIdentityCancelReqDTO cancelReqDTO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 查询要作废的记录
            QueryWrapper<TaxIdentityReport> queryWrapper = new QueryWrapper<>();

            if (Objects.nonNull(cancelReqDTO.getId())) {
                queryWrapper.eq("id", cancelReqDTO.getId());
            }

            if (cancelReqDTO.getIds() != null && !cancelReqDTO.getIds().isEmpty()) {
                queryWrapper.in("id", cancelReqDTO.getIds());
            }

            // 如果前面没加任何条件，就默认查待作废状态
            if (queryWrapper.getExpression().getNormal().isEmpty()) {
                queryWrapper.eq("report_status", ReportStatusEnums.WAIT_CANCEL.getCode());
            }

            List<TaxIdentityReport> records = taxIdentityReportMapper.selectList(queryWrapper);

            // 检查记录状态，只有已报送成功的记录才能作废
            List<TaxIdentityReport> validRecords = records.stream()
                    .filter(record -> record.getReportStatus() != null && record.getReportStatus().equals(ReportStatusEnums.WAIT_CANCEL.getCode()))
                    .collect(Collectors.toList());

            if (validRecords.isEmpty()) {
                result.put("success", false);
                result.put("message", "没有可作废的记录（只有待作废的记录才能作废）");
                return result;
            }

            // 分批处理，每批2000条
            List<List<TaxIdentityReport>> batches = splitIntoBatches(validRecords, 2000);
            int totalBatches = batches.size();

            log.info("身份信息作废：总数据{}条，拆分为{}个批次", validRecords.size(), totalBatches);

            int successCount = 0;
            int failCount = 0;
            int successBatches = 0;
            int failBatches = 0;
            String errorMessage = null;

            for (int batchIndex = 0; batchIndex < batches.size(); batchIndex++) {
                List<TaxIdentityReport> batchReports = batches.get(batchIndex);

                try {
                    // 更新批次中所有记录状态为报送中
                    for (TaxIdentityReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.CANCELING.getCode());
                        taxIdentityReportMapper.updateById(report);
                    }


                    // 构建作废请求数据
                    TaxReportRequest.IdentityCancelRequest identityCancelRequest = buildIdentityCancelData(batchReports);

                    // 构建压缩后的报送请求
                    DataCompressionUtil.TaxReportRequestWrapper compressedRequest =
                            DataCompressionUtil.buildTaxReportRequest(taxReportConfig.getIdentityCancelBusinessType(), identityCancelRequest);

                    // 调用作废接口
                    TaxReportResult cancelResult = callTaxReportApi("身份信息作废", taxReportConfig.getIdentityCancelUrl(), compressedRequest, batchIndex);

                    errorMessage = cancelResult.getDetailedErrorMessage();

                    if (cancelResult.isSuccess()) {
                        // 批量更新成功状态
                        for (TaxIdentityReport record : batchReports) {
                            record.setReportStatus(ReportStatusEnums.CANCEL_SUCCESS.getCode());
                            record.setReportMessage("作废成功");
                            record.setUpdateTime(LocalDateTime.now());
                            taxIdentityReportMapper.updateById(record);
                        }
                        successBatches++;
                        successCount += batchReports.size();
                        log.info("批次{}作废成功，明细数量：{}", batchIndex + 1, batchReports.size());
                    } else {
                        // 批量更新失败状态
                        for (TaxIdentityReport record : batchReports) {
                            record.setReportStatus(ReportStatusEnums.CANCEL_FAIL.getCode());
                            record.setReportMessage("作废失败: " + cancelResult.getDetailedErrorMessage());
                            record.setUpdateTime(LocalDateTime.now());
                            taxIdentityReportMapper.updateById(record);
                        }
                        failBatches++;
                        failCount += batchReports.size();
                        log.error("批次{}作废失败，明细数量：{}，错误信息：{}", batchIndex + 1, batchReports.size(), cancelResult.getDetailedErrorMessage());
                    }

                } catch (Exception e) {
                    log.error("批次{}作废异常，明细数量：{}", batchIndex + 1, batchReports.size(), e);

                    // 批量更新异常状态
                    for (TaxIdentityReport record : batchReports) {
                        record.setReportStatus(ReportStatusEnums.CANCEL_FAIL.getCode());
                        record.setReportMessage("作废异常: " + e.getMessage());
                        record.setUpdateTime(LocalDateTime.now());
                        taxIdentityReportMapper.updateById(record);
                    }
                    failBatches++;
                    failCount += batchReports.size();
                }
            }

            // 构建返回结果
            result.put("success", failBatches == 0);
            result.put("message", failBatches == 0 ? "身份信息作废完成" : "身份信息作废部分完成");
            result.put("errorMessage", errorMessage);
            result.put("totalCount", validRecords.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalBatches", totalBatches);
            result.put("successBatches", successBatches);
            result.put("failBatches", failBatches);

        } catch (Exception e) {
            log.error("身份信息作废失败", e);
            result.put("success", false);
            result.put("message", "身份信息作废失败: " + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> cancelIncomeData(TaxIncomeCancelReqDTO cancelReqDTO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 查询要作废的记录
            QueryWrapper<TaxIncomeReport> queryWrapper = new QueryWrapper<>();

            if (Objects.nonNull(cancelReqDTO.getId())) {
                queryWrapper.eq("id", cancelReqDTO.getId());
            }

            if (cancelReqDTO.getIds() != null && !cancelReqDTO.getIds().isEmpty()) {
                queryWrapper.in("id", cancelReqDTO.getIds());
            }

            // 如果前面没加任何条件，就默认查待作废状态
            if (queryWrapper.getExpression().getNormal().isEmpty()) {
                queryWrapper.eq("report_status", ReportStatusEnums.WAIT_CANCEL.getCode());
            }

            List<TaxIncomeReport> records = taxIncomeReportMapper.selectList(queryWrapper);

            if (records.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到要作废的记录");
                return result;
            }
            // 检查记录状态，只有已报送成功的记录才能作废
            List<TaxIncomeReport> validRecords = records.stream()
                    .filter(record -> record.getReportStatus() != null && record.getReportStatus().equals(ReportStatusEnums.WAIT_CANCEL.getCode()))
                    .collect(Collectors.toList());

            if (validRecords.isEmpty()) {
                result.put("success", false);
                result.put("message", "没有可作废的记录（只有待作废的记录才能作废）");
                return result;
            }

            // 分批处理，每批2000条
            List<List<TaxIncomeReport>> batches = splitIntoBatches(validRecords, 2000);
            int totalBatches = batches.size();

            log.info("收入信息作废：总数据{}条，拆分为{}个批次", validRecords.size(), totalBatches);

            int successCount = 0;
            int failCount = 0;
            int successBatches = 0;
            int failBatches = 0;
            String errorMessage = null;

            for (int batchIndex = 0; batchIndex < batches.size(); batchIndex++) {
                List<TaxIncomeReport> batchReports = batches.get(batchIndex);

                try {

                    // 更新批次中所有记录状态为报送中
                    for (TaxIncomeReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.CANCELING.getCode());
                        taxIncomeReportMapper.updateById(report);
                    }
                    // 构建作废请求数据
                    TaxReportRequest.IncomeCancelRequest incomeCancelRequest = buildIncomeCancelData(batchReports);

                    // 构建压缩后的报送请求
                    DataCompressionUtil.TaxReportRequestWrapper compressedRequest =
                            DataCompressionUtil.buildTaxReportRequest(taxReportConfig.getIncomeCancelBusinessType(), incomeCancelRequest);

                    // 调用作废接口
                    TaxReportResult cancelResult = callTaxReportApi("收入信息作废", taxReportConfig.getIncomeCancelUrl(), compressedRequest, batchIndex);

                    errorMessage = cancelResult.getDetailedErrorMessage();

                    if (cancelResult.isSuccess()) {
                        // 批量更新成功状态
                        for (TaxIncomeReport record : batchReports) {
                            record.setReportStatus(ReportStatusEnums.CANCEL_SUCCESS.getCode());
                            record.setReportMessage("作废成功");
                            record.setUpdateTime(LocalDateTime.now());
                            taxIncomeReportMapper.updateById(record);
                        }
                        successBatches++;
                        successCount += batchReports.size();
                        log.info("批次{}作废成功，明细数量：{}", batchIndex + 1, batchReports.size());
                    } else {
                        // 批量更新失败状态
                        for (TaxIncomeReport record : batchReports) {
                            record.setReportStatus(ReportStatusEnums.CANCEL_FAIL.getCode());
                            record.setReportMessage("作废失败: " + cancelResult.getDetailedErrorMessage());
                            record.setUpdateTime(LocalDateTime.now());
                            taxIncomeReportMapper.updateById(record);
                        }
                        failBatches++;
                        failCount += batchReports.size();
                        log.error("批次{}作废失败，明细数量：{}，错误信息：{}", batchIndex + 1, batchReports.size(), cancelResult.getDetailedErrorMessage());
                    }

                } catch (Exception e) {
                    log.error("批次{}作废异常，明细数量：{}", batchIndex + 1, batchReports.size(), e);

                    // 批量更新异常状态
                    for (TaxIncomeReport record : batchReports) {
                        record.setReportStatus(ReportStatusEnums.CANCEL_FAIL.getCode());
                        record.setReportMessage("作废异常: " + e.getMessage());
                        record.setUpdateTime(LocalDateTime.now());
                        taxIncomeReportMapper.updateById(record);
                    }
                    failBatches++;
                    failCount += batchReports.size();
                }
            }

            // 构建返回结果
            result.put("success", failBatches == 0);
            result.put("message", failBatches == 0 ? "收入信息作废完成" : "收入信息作废部分完成");
            result.put("errorMessage", errorMessage);
            result.put("totalCount", validRecords.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalBatches", totalBatches);
            result.put("successBatches", successBatches);
            result.put("failBatches", failBatches);

        } catch (Exception e) {
            log.error("收入信息作废失败", e);
            result.put("success", false);
            result.put("message", "收入信息作废失败: " + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> cancelPlatformData(TaxPlatformCancelReqDTO cancelReqDTO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 查询要作废的记录
            QueryWrapper<TaxPlatformReport> queryWrapper = new QueryWrapper<>();

            if (Objects.nonNull(cancelReqDTO.getId())) {
                queryWrapper.eq("id", cancelReqDTO.getId());
            }

            if (cancelReqDTO.getIds() != null && !cancelReqDTO.getIds().isEmpty()) {
                queryWrapper.in("id", cancelReqDTO.getIds());
            }

            // 如果前面没加任何条件，就默认查待作废状态
            if (queryWrapper.getExpression().getNormal().isEmpty()) {
                queryWrapper.eq("report_status", ReportStatusEnums.WAIT_CANCEL.getCode());
            }

            List<TaxPlatformReport> records = taxPlatformReportMapper.selectList(queryWrapper);

            if (records.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到要作废的记录");
                return result;
            }

            // 检查记录状态，只有已报送成功的记录才能作废
            List<TaxPlatformReport> validRecords = records.stream()
                    .filter(record -> record.getReportStatus() != null && record.getReportStatus().equals(ReportStatusEnums.WAIT_CANCEL.getCode()))
                    .collect(Collectors.toList());

            if (validRecords.isEmpty()) {
                result.put("success", false);
                result.put("message", "没有可作废的记录（只有待作废的记录才能作废）");
                return result;
            }

            // 分批处理，每批2000条
            List<List<TaxPlatformReport>> batches = splitIntoBatches(validRecords, 2000);
            int totalBatches = batches.size();

            log.info("平台信息作废：总数据{}条，拆分为{}个批次", validRecords.size(), totalBatches);

            int successCount = 0;
            int failCount = 0;
            int successBatches = 0;
            int failBatches = 0;
            String errorMessage = null;

            for (int batchIndex = 0; batchIndex < batches.size(); batchIndex++) {
                List<TaxPlatformReport> batchReports = batches.get(batchIndex);

                try {
                    // 更新批次中所有记录状态为报送中
                    for (TaxPlatformReport report : batchReports) {
                        report.setReportStatus(ReportStatusEnums.CANCELING.getCode());
                        taxPlatformReportMapper.updateById(report);
                    }
                    // 构建作废请求数据
                    TaxReportRequest.PlatformCancelRequest platformCancelRequest = buildPlatformCancelData(batchReports);

                    // 构建压缩后的报送请求
                    DataCompressionUtil.TaxReportRequestWrapper compressedRequest =
                            DataCompressionUtil.buildTaxReportRequest(taxReportConfig.getPlatformCancelBusinessType(), platformCancelRequest);

                    // 调用作废接口
                    TaxReportResult cancelResult = callTaxReportApi("平台信息作废", taxReportConfig.getPlatformCancelUrl(), compressedRequest, batchIndex);

                    errorMessage = cancelResult.getDetailedErrorMessage();

                    if (cancelResult.isSuccess()) {
                        // 批量更新成功状态
                        for (TaxPlatformReport record : batchReports) {
                            record.setReportStatus(ReportStatusEnums.CANCEL_SUCCESS.getCode());
                            record.setReportMessage("作废成功");
                            record.setUpdateTime(LocalDateTime.now());
                            taxPlatformReportMapper.updateById(record);
                        }
                        successBatches++;
                        successCount += batchReports.size();
                        log.info("批次{}作废成功，明细数量：{}", batchIndex + 1, batchReports.size());
                    } else {
                        // 批量更新失败状态
                        for (TaxPlatformReport record : batchReports) {
                            record.setReportStatus(ReportStatusEnums.CANCEL_FAIL.getCode());
                            record.setReportMessage("作废失败: " + cancelResult.getDetailedErrorMessage());
                            record.setUpdateTime(LocalDateTime.now());
                            taxPlatformReportMapper.updateById(record);
                        }
                        failBatches++;
                        failCount += batchReports.size();
                        log.error("批次{}作废失败，明细数量：{}，错误信息：{}", batchIndex + 1, batchReports.size(), cancelResult.getDetailedErrorMessage());
                    }

                } catch (Exception e) {
                    log.error("批次{}作废异常，明细数量：{}", batchIndex + 1, batchReports.size(), e);

                    // 批量更新异常状态
                    for (TaxPlatformReport record : batchReports) {
                        record.setReportStatus(ReportStatusEnums.CANCEL_FAIL.getCode());
                        record.setReportMessage("作废异常: " + e.getMessage());
                        record.setUpdateTime(LocalDateTime.now());
                        taxPlatformReportMapper.updateById(record);
                    }
                    failBatches++;
                    failCount += batchReports.size();
                }
            }

            // 构建返回结果
            result.put("success", failBatches == 0);
            result.put("message", failBatches == 0 ? "平台信息作废完成" : "平台信息作废部分完成");
            result.put("errorMessage", errorMessage);
            result.put("totalCount", validRecords.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalBatches", totalBatches);
            result.put("successBatches", successBatches);
            result.put("failBatches", failBatches);

        } catch (Exception e) {
            log.error("平台信息作废失败", e);
            result.put("success", false);
            result.put("message", "平台信息作废失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 构建批量身份信息报送请求
     */
    private TaxReportRequest.IdentityReportRequest buildBatchIdentityReportRequest(List<TaxIdentityReport> reports) {
        TaxReportRequest.IdentityReportRequest request = new TaxReportRequest.IdentityReportRequest();

        // 设置基本信息
        request.setPtqymc(taxReportConfig.getConfig().get("ptqymc"));
        request.setPtqytyshxydm(taxReportConfig.getConfig().get("ptqytyshxydm"));
        request.setPtuuid(taxReportConfig.getConfig().get("ptuuid"));
        request.setPthyycxmc(taxReportConfig.getConfig().get("pthyycxmc"));
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        request.setBsrq1(df.format(LocalDate.now())); // 批量报送时使用当前日期
        request.setDqwsfxxxybs("N"); // 默认有数据需要报送
        request.setJbr(taxReportConfig.getConfig().get("jbr"));
        request.setJbrlxfs(taxReportConfig.getConfig().get("jbrlxfs"));

        // 构建身份明细列表
        List<TaxReportRequest.IdentityReportRequest.IdentityDetail> details = new ArrayList<>();
        for (TaxIdentityReport report : reports) {
            TaxReportRequest.IdentityReportRequest.IdentityDetail detail = new TaxReportRequest.IdentityReportRequest.IdentityDetail();
            detail.setSfblscztdj(report.getHasRegistration() == 1 ? "Y" : "N");
            detail.setNsrmc(report.getHasRegistration() == 1 ? report.getTaxpayerName() : null);
            detail.setZyfwjgbsDm(report.getHasRegistration() == 1 ? report.getProfessionalServiceIdentifier() : null);
            detail.setShxydm(report.getHasRegistration() == 1 ? report.getCreditCode() : null);
            detail.setXm(report.getHasRegistration() == 0 ? report.getMerchantName() : null);
            detail.setShxydm(report.getHasRegistration() == 1 ? report.getCreditCode() : null);
            detail.setZjhm1(report.getHasRegistration() == 0 ? report.getCreditCode() : null);
            detail.setGjhdqszDm(report.getHasRegistration() == 0 ? "156" : null);
            detail.setSfczhmbsqx("N");
            detail.setXxdz(report.getDetailedAddress());
            detail.setYhdpwybsm(report.getMerchantId());
            detail.setYhdpmc(report.getMerchantName());
            detail.setDpwz(report.getWebsite());
            detail.setLxrxm(report.getContactPerson());
            detail.setLxdh(report.getContactPhone());
            detail.setJszhxx(report.getSettlementAccountInfo());
            detail.setJykssj(df.format(report.getBusinessStartTime()));
            detail.setCzlxDm("01"); // 默认新增
            details.add(detail);
        }
        request.setSfxxmx(details);

        return request;
    }

    /**
     * 构建批量收入信息报送请求
     */
    private TaxReportRequest.IncomeReportRequest buildBatchIncomeReportRequest(List<TaxIncomeReport> reports) {
        TaxReportRequest.IncomeReportRequest request = new TaxReportRequest.IncomeReportRequest();

        // 设置基本信息
        request.setPtqymc(taxReportConfig.getConfig().get("ptqymc"));
        request.setPtqytyshxydm(taxReportConfig.getConfig().get("ptqytyshxydm"));
        request.setPtuuid(taxReportConfig.getConfig().get("ptuuid"));
        request.setPthyycxmc(taxReportConfig.getConfig().get("pthyycxmc"));
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        request.setBsrq1(df.format(LocalDate.now())); // 批量报送时使用当前日期
        request.setDqwsrxxxybs("N"); // 默认有数据需要报送
        request.setSrxxssqq(reports.get(0).getStartTime());
        request.setSrxxssqz(reports.get(0).getEndTime());
        request.setJbr(taxReportConfig.getConfig().get("jbr"));
        request.setJbrlxfs(taxReportConfig.getConfig().get("jbrlxfs"));

        // 构建收入明细列表
        List<TaxReportRequest.IncomeReportRequest.IncomeDetail> details = new ArrayList<>();
        for (TaxIncomeReport report : reports) {
            TaxReportRequest.IncomeReportRequest.IncomeDetail detail = new TaxReportRequest.IncomeReportRequest.IncomeDetail();
            detail.setSfblscztdj(report.getHasRegistration() == 1 ? "Y" : "N");
            detail.setNsrmc(report.getHasRegistration() == 1 ? report.getTaxpayerName() : null);
            detail.setShxydm(report.getHasRegistration() == 1 ? report.getCreditCode() : null);
            detail.setXm(report.getHasRegistration() == 0 ? report.getMerchantName() : null);
            detail.setZjhm1(report.getHasRegistration() == 0 ? report.getCreditCode() : null);
            detail.setGjhdqszDm(report.getHasRegistration() == 0 ? "156" : null);
            detail.setSrlydhlwptmc(taxReportConfig.getConfig().get("pthyycxmc"));
            detail.setYhdpwybsm(report.getMerchantId());
            detail.setYhdpmc(report.getMerchantName());
            detail.setYqddjzzdxshwsrze(report.getHasRegistration() == 1 ? report.getGoodsIncome() : null);
            detail.setYqddjzzdxshwtkje(report.getHasRegistration() == 1 ? report.getGoodsRefund() : null);
            detail.setYqddjzzdxswxzcsrze(report.getHasRegistration() == 1 ? report.getIntangibleIncome() : null);
            detail.setYqddjzzdxswxzctkje(report.getHasRegistration() == 1 ? report.getIntangibleRefund() : null);
            detail.setYqddjzzdxsfwsrze(report.getHasRegistration() == 1 ? report.getServiceIncome() : null);
            detail.setYqddjzzdxsfwtkje(report.getHasRegistration() == 1 ? report.getServiceRefund() : null);
            detail.setWqddjzzdsrze(report.getHasRegistration() == 0 ? report.getUnregisteredIncome() : null);
            detail.setWqddjzzdtkje(report.getHasRegistration() == 0 ? report.getUnregisteredRefund() : null);
            detail.setWqddjzzdsrjexshw(report.getHasRegistration() == 0 ? report.getNetIncomeGoods() : null);
            detail.setWqddjzzdsrjehwysfw(report.getHasRegistration() == 0 ? report.getNetIncomeTransport() : null);
            detail.setWqddjzzdsrjelwbc(report.getHasRegistration() == 0 ? report.getNetIncomeLabor() : null);
            detail.setWqddjzzdsrjegc(report.getHasRegistration() == 0 ? report.getNetIncomeRoyalty() : null);
            detail.setWqddjzzdsrjetxqsyf(report.getHasRegistration() == 0 ? report.getNetIncomeFranchise() : null);
            detail.setCsqtwljyhdqddsr(report.getOtherNetIncome());
            detail.setZfgptdyjfwfhjje(report.getPlatformCommission());
            detail.setDdsl(report.getTransactionCount());
            details.add(detail);
        }
        request.setSrxxmx(details);

        return request;
    }


    /**
     * 构建批量平台信息报送请求
     */
    private TaxReportRequest.PlatformReportRequest buildBatchPlatformReportRequest(List<TaxPlatformReport> reports) {
        TaxReportRequest.PlatformReportRequest request = new TaxReportRequest.PlatformReportRequest();

        // 设置基本信息
        request.setPtqymc(taxReportConfig.getConfig().get("ptqymc"));
        request.setPtqytyshxydm(taxReportConfig.getConfig().get("ptqytyshxydm"));
        request.setPtuuid(taxReportConfig.getConfig().get("ptuuid"));
        request.setPthyycxmc(taxReportConfig.getConfig().get("pthyycxmc"));
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        request.setBsrq1(df.format(LocalDate.now())); // 批量报送时使用当前日期
        request.setDqwptqysfxxxybs("N"); // 默认有数据需要报送
        request.setJbr(taxReportConfig.getConfig().get("jbr"));
        request.setJbrlxfs(taxReportConfig.getConfig().get("jbrlxfs"));

        // 构建平台明细列表
        List<TaxReportRequest.PlatformReportRequest.PlatformDetail> details = new ArrayList<>();
        for (TaxPlatformReport report : reports) {
            TaxReportRequest.PlatformReportRequest.PlatformDetail detail = new TaxReportRequest.PlatformReportRequest.PlatformDetail();
            detail.setNsrmc(report.getTaxpayerName());
            detail.setShxydm(report.getCreditCode());
            detail.setPthyycxmc(report.getPlatformName());
            detail.setPtndptwybsm(report.getPlatformId());
            detail.setJykssj(df.format(report.getBusinessStartTime()));
            detail.setCzlxDm("01"); // 默认新增
            details.add(detail);
        }
        request.setSfxxmx(details);

        return request;
    }

    /**
     * 构建身份信息作废数据
     */
    private TaxReportRequest.IdentityCancelRequest buildIdentityCancelData(List<TaxIdentityReport> records) {

        TaxReportRequest.IdentityCancelRequest request = new TaxReportRequest.IdentityCancelRequest();
        request.setPtqymc(taxReportConfig.getConfig().get("ptqymc"));
        request.setPtqytyshxydm(taxReportConfig.getConfig().get("ptqytyshxydm"));
        request.setPtuuid(taxReportConfig.getConfig().get("ptuuid"));
        request.setPthyycxmc(taxReportConfig.getConfig().get("pthyycxmc"));
        request.setBsrq1(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        request.setJbr(taxReportConfig.getConfig().get("jbr"));
        request.setJbrlxfs(taxReportConfig.getConfig().get("jbrlxfs"));

        List<TaxReportRequest.IdentityCancelRequest.IdentityCancelDetail> details = new ArrayList<>();

        for (TaxIdentityReport record : records) {
            TaxReportRequest.IdentityCancelRequest.IdentityCancelDetail detail = new TaxReportRequest.IdentityCancelRequest.IdentityCancelDetail();
            detail.setSfblscztdj(record.getHasRegistration() == 1 ? "Y" : "N");
            detail.setNsrmc(record.getHasRegistration() == 1 ? record.getTaxpayerName() : "");
            detail.setShxydm(record.getHasRegistration() == 1 ? record.getCreditCode() : "");
            detail.setXm(record.getHasRegistration() == 0 ? record.getTaxpayerName() : "");
            detail.setSfzjlxDm(record.getHasRegistration() == 0 ? "201" : "");
            detail.setZjhm1(record.getHasRegistration() == 0 ? record.getCreditCode() : "");
            detail.setGjhdqszDm(record.getHasRegistration() == 0 ? "156" : "");
            detail.setYhdpwybsm(record.getMerchantId());
            details.add(detail);

        }
        request.setSfxxmx(details);
        return request;
    }

    /**
     * 构建收入信息作废数据
     */
    private TaxReportRequest.IncomeCancelRequest buildIncomeCancelData(List<TaxIncomeReport> records) {
        // 从第一条记录获取平台信息
        TaxIncomeReport firstRecord = records.get(0);
        TaxReportRequest.IncomeCancelRequest request = new TaxReportRequest.IncomeCancelRequest();

        request.setPtqymc(taxReportConfig.getConfig().get("ptqymc"));
        request.setPtqytyshxydm(taxReportConfig.getConfig().get("ptqytyshxydm"));
        request.setPtuuid(taxReportConfig.getConfig().get("ptuuid"));
        request.setPthyycxmc(taxReportConfig.getConfig().get("pthyycxmc"));
        request.setBsrq1(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        request.setSrxxssqq(firstRecord.getStartTime());
        request.setSrxxssqz(firstRecord.getEndTime());
        request.setJbr(taxReportConfig.getConfig().get("jbr"));
        request.setJbrlxfs(taxReportConfig.getConfig().get("jbrlxfs"));

        List<TaxReportRequest.IncomeCancelRequest.IncomeCancelDetail> details = new ArrayList<>();

        for (TaxIncomeReport record : records) {
            TaxReportRequest.IncomeCancelRequest.IncomeCancelDetail detail = new TaxReportRequest.IncomeCancelRequest.IncomeCancelDetail();
            detail.setSfblscztdj(record.getHasRegistration() == 1 ? "Y" : "N");
            detail.setNsrmc(record.getHasRegistration() == 1 ? record.getTaxpayerName() : "");
            detail.setShxydm(record.getHasRegistration() == 1 ? record.getCreditCode() : "");
            detail.setXm(record.getHasRegistration() == 0 ? record.getTaxpayerName() : "");
            detail.setSfzjlxDm(record.getHasRegistration() == 0 ? "201" : "");
            detail.setZjhm1(record.getHasRegistration() == 0 ? record.getCreditCode() : "");
            detail.setGjhdqszDm(record.getHasRegistration() == 0 ? "156" : "");
            detail.setYhdpwybsm(record.getMerchantId());
            detail.setSrlydhlwptmc(record.getMerchantName());
            details.add(detail);
        }
        request.setSrxxmx(details);
        return request;
    }

    /**
     * 构建平台信息作废数据
     */
    private TaxReportRequest.PlatformCancelRequest buildPlatformCancelData(List<TaxPlatformReport> records) {

        TaxReportRequest.PlatformCancelRequest request = new TaxReportRequest.PlatformCancelRequest();
        request.setPtqymc(taxReportConfig.getConfig().get("ptqymc"));
        request.setPtqytyshxydm(taxReportConfig.getConfig().get("ptqytyshxydm"));
        request.setPtuuid(taxReportConfig.getConfig().get("ptuuid"));
        request.setPthyycxmc(taxReportConfig.getConfig().get("pthyycxmc"));
        request.setBsrq1(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        request.setJbr(taxReportConfig.getConfig().get("jbr"));
        request.setJbrlxfs(taxReportConfig.getConfig().get("jbrlxfs"));

        List<TaxReportRequest.PlatformCancelRequest.PlatformCancelDetail> details = new ArrayList<>();
        for (TaxPlatformReport record : records) {
            TaxReportRequest.PlatformCancelRequest.PlatformCancelDetail detail = new TaxReportRequest.PlatformCancelRequest.PlatformCancelDetail();
            detail.setNsrmc(record.getTaxpayerName()); // 名称（姓名）
            detail.setShxydm(record.getCreditCode()); // 统一社会信用代码（纳税人识别号）
            detail.setPthyycxmc(record.getPlatformName()); // 平台内的平台名称
            detail.setPtndptwybsm(record.getPlatformId()); // 平台内的平台唯一标识码
            details.add(detail);

        }
        request.setSfxxmx(details);
        return request;
    }


    /**
     * 调用税务报送接口
     */
    private TaxReportResult callTaxReportApi(String apiName, String apiUrl, Object requestBody, Integer recordId) {
        long startTime = System.currentTimeMillis();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        // 发送请求
        ResponseEntity<String> response = null;
        try {

            headers.setContentType(MediaType.APPLICATION_JSON);

            // 添加税务报送专用请求头
//            taxReportConfig.getHeaders().forEach(headers::add);

            if (taxReportConfig.getHeaders() != null) {
                String clientTid = ("tid_" + UUID.randomUUID().toString().replace("-", "")).substring(0, 32);
                taxReportConfig.getHeaders().put("clientTid", clientTid);
                taxReportConfig.getHeaders().forEach(headers::add);

            }

            // 创建请求实体
            String encrypt = Sm4Util.encryptWithSm4Ecb(JSON.toJSONString(requestBody), taxReportConfig.getPlatformSecret());
            log.info("请求报文：{}", encrypt);
            HttpEntity<Object> requestEntity = new HttpEntity<>(encrypt, headers);

            // 发送请求
            response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            long executionTime = System.currentTimeMillis() - startTime;

            // 解析响应
            String responseBody = response.getBody();
            if (responseBody == null) {
                // 记录API调用日志
                recordApiLog(apiName, apiUrl, headers, requestBody, null, 0, executionTime, 0, "响应体为空");
                return TaxReportResult.failure("响应体为空");
            }

            // 解析HTTP状态码
            Integer httpStatusCode = null;
            try {
                JSONObject responseJson = JSON.parseObject(responseBody);
                httpStatusCode = responseJson.getInteger("httpStatusCode");
            } catch (Exception e) {
                log.error("解析响应JSON失败，响应体：{}", responseBody, e);
                recordApiLog(apiName, apiUrl, headers, requestBody, responseBody, 0, executionTime, 0, "解析响应JSON失败");
                return TaxReportResult.failure("解析响应JSON失败: " + e.getMessage());
            }

            // 记录API调用日志
            recordApiLog(apiName, apiUrl, headers, requestBody, responseBody, httpStatusCode, executionTime, 1, null);

            // 检查HTTP状态码
            if (httpStatusCode != 200) {
                log.warn("税务报送接口调用失败，API：{}，记录ID：{}，HTTP状态码：{}，响应：{}",
                        apiName, recordId, httpStatusCode, responseBody);
                JSONObject responseJson = JSON.parseObject(responseBody);
                String bodyStr = responseJson.getString("body");
                return TaxReportResult.failure(bodyStr, httpStatusCode, responseBody);
            }

            // HTTP状态码为200，需要解密Data字段
            try {
                JSONObject responseJson = JSON.parseObject(responseBody);
                String bodyStr = responseJson.getString("body");

                if (bodyStr == null) {
                    log.error("响应体中body字段为空，API：{}，记录ID：{}", apiName, recordId);
                    return TaxReportResult.failure("响应体中body字段为空", httpStatusCode, responseBody);
                }

                // 解析body字段
                JSONObject bodyJson = JSON.parseObject(bodyStr);
                JSONObject responseResultJson = bodyJson.getJSONObject("Response");  // 先获取Response对象

                if (responseResultJson == null) {
                    log.error("响应体中Response字段为空，API：{}，记录ID：{}", apiName, recordId);
                    return TaxReportResult.failure("响应体中Response字段为空", httpStatusCode, responseBody);
                }

                String dataStr = responseResultJson.getString("Data");  // 从Response中获取Data

                // 解密Data字段
                String decryptedData = Sm4Util.decryptWithSm4Ecb(dataStr, taxReportConfig.getPlatformSecret());
                if (decryptedData == null) {
                    log.error("解密Data字段失败，API：{}，记录ID：{}", apiName, recordId);
                    return TaxReportResult.failure("解密Data字段失败", httpStatusCode, responseBody);
                }
                if (dataStr == null) {
                    log.error("响应体中Data字段为空，API：{}，记录ID：{}", apiName, recordId);
                    return TaxReportResult.failure("响应体中Data字段为空", httpStatusCode, responseBody);
                }

                // 解析解密后的数据
                JSONObject decryptedJson = JSON.parseObject(decryptedData);
                String wzxjyycsjl = decryptedJson.getString("wzxjyycsjl");
                String detail = null;
                if (!ObjectUtils.isEmpty(wzxjyycsjl)) {
                    detail = DataCompressionUtil.decompressFromGzipBase64(wzxjyycsjl);
                }

                String returnCode = decryptedJson.getString("returncode");

                if ("00".equals(returnCode)) {
                    log.info("税务报送接口调用成功，API：{}，记录ID：{}，returncode：{}", apiName, recordId, returnCode);
                    return TaxReportResult.success(decryptedJson, httpStatusCode, responseBody);
                } else {
                    String errorMsg = decryptedJson.getString("returnmsg") != null ?
                            decryptedJson.getString("returnmsg") : "returncode非00";
                    errorMsg = errorMsg + detail;
                    log.warn("税务报送接口调用失败，API：{}，记录ID：{}，returncode：{}，错误信息：{}",
                            apiName, recordId, returnCode, errorMsg);
                    return TaxReportResult.failure("业务处理失败: " + errorMsg, httpStatusCode, responseBody);
                }

            } catch (Exception e) {
                log.error("处理响应数据失败，API：{}，记录ID：{}，响应：{}", apiName, recordId, responseBody, e);
                return TaxReportResult.failure("处理响应数据失败: " + e.getMessage(), httpStatusCode, responseBody);
            }

        } catch (Exception e) {
            long executionTime = System.currentTimeMillis() - startTime;

            // 记录失败日志
            recordApiLog(apiName, apiUrl, headers, requestBody, null, 0, executionTime, 0, e.getMessage());

            log.error("调用税务报送接口失败，API：{}，URL：{}，记录ID：{}", apiName, apiUrl, recordId, e);
            return TaxReportResult.failure("调用接口异常: " + e.getMessage());
        }
    }

    /**
     * 记录API调用日志
     */
    private void recordApiLog(String apiName, String apiUrl, HttpHeaders headers, Object requestBody,
                              String responseBody, Integer responseCode, long executionTime,
                              Integer status, String errorMessage) {
        try {
            TaxApiLog apiLog = new TaxApiLog();
            apiLog.setApiName(apiName);
            apiLog.setApiUrl(apiUrl);
            apiLog.setRequestMethod("POST");
            apiLog.setRequestHeaders(JSON.toJSONString(headers.toSingleValueMap()));
            apiLog.setRequestBody(JSON.toJSONString(requestBody));
            apiLog.setResponseCode(responseCode);
            apiLog.setResponseHeaders(responseBody != null ? JSON.toJSONString(new HashMap<>()) : null);
            apiLog.setResponseBody(responseBody);
            apiLog.setExecutionTime(executionTime);
            apiLog.setStatus(status);
            apiLog.setErrorMessage(errorMessage);
            apiLog.setCreateTime(LocalDateTime.now());

            taxApiLogMapper.insert(apiLog);
        } catch (Exception e) {
            log.error("记录API调用日志失败", e);
        }
    }

    @Override
    public Map<String, Object> getReportStatistics() {
        Map<String, Object> statistics = new HashMap<>();

        try {
            // 统计收入信息报送状态
            QueryWrapper<TaxIncomeReport> incomeQuery = new QueryWrapper<>();
            incomeQuery.select("report_status", "COUNT(*) as count")
                    .groupBy("report_status");
            List<Map<String, Object>> incomeStats = taxIncomeReportMapper.selectMaps(incomeQuery);

            Map<String, Object> incomeData = new HashMap<>();
            incomeData.put("pending", 0);
            incomeData.put("success", 0);
            incomeData.put("failed", 0);

            for (Map<String, Object> stat : incomeStats) {
                Integer status = (Integer) stat.get("report_status");
                Long count = (Long) stat.get("count");
                if (status == 0) {
                    incomeData.put("pending", count);
                } else if (status == 2) {
                    incomeData.put("success", count);
                } else if (status == 3) {
                    incomeData.put("failed", count);
                }
            }
            statistics.put("income", incomeData);

            // 统计身份信息报送状态
            QueryWrapper<TaxIdentityReport> identityQuery = new QueryWrapper<>();
            identityQuery.select("report_status", "COUNT(*) as count")
                    .groupBy("report_status");
            List<Map<String, Object>> identityStats = taxIdentityReportMapper.selectMaps(identityQuery);

            Map<String, Object> identityData = new HashMap<>();
            identityData.put("pending", 0);
            identityData.put("success", 0);
            identityData.put("failed", 0);

            for (Map<String, Object> stat : identityStats) {
                Integer status = (Integer) stat.get("report_status");
                Long count = (Long) stat.get("count");
                if (status == 0) {
                    identityData.put("pending", count);
                } else if (status == 2) {
                    identityData.put("success", count);
                } else if (status == 3) {
                    identityData.put("failed", count);
                }
            }
            statistics.put("identity", identityData);

            // 统计平台信息报送状态
            QueryWrapper<TaxPlatformReport> platformQuery = new QueryWrapper<>();
            platformQuery.select("report_status", "COUNT(*) as count")
                    .groupBy("report_status");
            List<Map<String, Object>> platformStats = taxPlatformReportMapper.selectMaps(platformQuery);

            Map<String, Object> platformData = new HashMap<>();
            platformData.put("pending", 0);
            platformData.put("success", 0);
            platformData.put("failed", 0);

            for (Map<String, Object> stat : platformStats) {
                Integer status = (Integer) stat.get("report_status");
                Long count = (Long) stat.get("count");
                if (status == 0) {
                    platformData.put("pending", count);
                } else if (status == 2) {
                    platformData.put("success", count);
                } else if (status == 3) {
                    platformData.put("failed", count);
                }
            }
            statistics.put("platform", platformData);

            // 添加时间戳
            statistics.put("timestamp", System.currentTimeMillis());

            log.info("获取报送统计信息成功：{}", statistics);

        } catch (Exception e) {
            log.error("获取报送统计信息失败", e);
            // 返回空统计信息
            Map<String, Integer> emptyMap = new HashMap<>();
            emptyMap.put("pending", 0);
            emptyMap.put("success", 0);
            emptyMap.put("failed", 0);

            statistics.put("income", emptyMap);
            statistics.put("identity", emptyMap);
            statistics.put("platform", emptyMap);
            statistics.put("timestamp", System.currentTimeMillis());
        }

        return statistics;
    }

    @Override
    public String getPtUUID() throws Exception {
        TaxPlatformRequest request = new TaxPlatformRequest();
        request.setShxydm(taxReportConfig.getConfig().get("ptqytyshxydm"));
        request.setPthyycxmc(taxReportConfig.getConfig().get("pthyycxmc"));
        TaxReportResult reportResult = callTaxReportApi("获取平台UUID", taxReportConfig.getPtUuidUrl(), request, null);
        log.info(JSON.toJSONString(reportResult));
        String errorMessage = reportResult.getDetailedErrorMessage();
        if (reportResult.isSuccess()) {
            log.info("批次{}报送成功，明细数量：{}");
            return reportResult.getDecryptedData().toString();
        } else {
            throw new Exception(errorMessage);
        }
    }

    /**
     * 将列表按指定大小拆分成多个子列表
     */
    private <T> List<List<T>> splitIntoBatches(List<T> source, int batchSize) {
        List<List<T>> batches = new ArrayList<>();
        for (int i = 0; i < source.size(); i += batchSize) {
            batches.add(new ArrayList<>(source.subList(i, Math.min(i + batchSize, source.size()))));
        }
        return batches;
    }

}
